package br.unisul.prolinear.controller;

import java.io.IOException;

import javax.faces.context.FacesContext;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import br.unisul.prolinear.dao.UsuarioDaoImp;
import br.unisul.prolinear.utils.Util;

public class LoginController extends Controller{
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public String doLogin() throws IOException{
		FacesContext.getCurrentInstance().getExternalContext().dispatch("/j_spring_security_check");
		FacesContext.getCurrentInstance().responseComplete();

		Authentication authentication = (Authentication) SecurityContextHolder.getContext().getAuthentication(); 
		if(authentication != null){
			String email = authentication.getName();
			UsuarioDaoImp dao = new UsuarioDaoImp();
			usuario = dao.get("email", email);
			dao.incrementaAcessos(usuario);
			SystemController.setUsuario(usuario);
		}
		return null;
	}
	
	public  String doLogout(){
		SystemController.setUsuario(null);
		Util.redirect("../../j_spring_security_logout");
		return null;
	}
	
	public void redirecionaPaginaInicial(){
		if(isAlunoLogado()){
			Util.redirect("pages/user/home.jsf");
		}else{
			Util.redirect("pages/admin/homeAdm.jsf");
		}
	}
}
